#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash ambertools-21.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] && echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] && echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum -y install cmake time boost bzip2 bzip2-devel bison flex libXt-devel libXext-devel tcsh make \
    which flex bison patch bc \
    perl perl-ExtUtils-MakeMaker util-linux wget \
    bzip2 bzip2-devel zlib-devel tar
set -e
wget -t 50 -c "https://ambermd.org/cgi-bin/AmberTools21-get.pl?Name=test&Institution=test&City=test&State=ON&Country=AI" -O "$buildpath"/AmberTools21.tar.bz2

tar -xvf "$buildpath"/AmberTools21.tar.bz2 -C "$buildpath" && rm -rf "$buildpath"/AmberTools21.tar.bz2

cp cmake.defaults.patch "$buildpath"/amber20_src

cd "$buildpath"/amber20_src

./update_amber --update
patch -p2 <./cmake.defaults.patch
cd build/
export CMAKE_PREFIX_PATH=$installpath/openblas
FLAGS="-mcpu=tsv110 -ffp-contract=off -I$installpath/hmpi-1.1.1/hmpi-1.1.1-huawei/include"
cmake .. \
    -DCMAKE_INSTALL_PREFIX="$installpath"/ambertools21 \
    -DCOMPILER=AUTO \
    -DCMAKE_C_FLAGS="$FLAGS" \
    -DFORCE_EXTERNAL_LIBS=blas \
    -DCMAKE_CXX_FLAGS="$FLAGS" \
    -DCMAKE_Fortran_FLAGS="$FLAGS" \
    -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_Fortran_COMPILER=flang \
    -DMPI=TRUE -DCUDA=FALSE -DOPENMP=TRUE -DINSTALL_TESTS=TRUE \
    -DDOWNLOAD_MINICONDA=FALSE -DMINICONDA_USE_PY3=FALSE

sed -i "s/-o CMakeFiles\/cifparse.dir\/cifparse.c.o/-fcommon  -o CMakeFiles\/cifparse.dir\/cifparse.c.o/g" AmberTools/src/cifparse/CMakeFiles/cifparse.dir/build.make
sed -i "s/-o CMakeFiles\/cifparse.dir\/cifp.tab.c.o/-fcommon  -o CMakeFiles\/cifparse.dir\/cifp.tab.c.o/g" AmberTools/src/cifparse/CMakeFiles/cifparse.dir/build.make
make -j 8
make -j install
echo './sander-16.0-py3.8-linux-aarch64.egg' >>"$installpath"/ambertools21/lib/python3.8/site-packages/easy-install.pth
echo './ParmEd-3.4.1-py3.8-linux-aarch64.egg' >>"$installpath"/ambertools21/lib/python3.8/site-packages/easy-install.pth
rm -rf "$buildpath"/amber20_src
